<?php

namespace App\Http\Controllers\Api\v1;

use App\Events\LoginEvent;
use App\Http\Controllers\BaseController;
use App\Transformers\UserTransformer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\Authorization;
use App\Transformers\AuthorizationTransformer;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Validator;

class AuthController extends BaseController
{
    /**
     * Create a new AuthController instance.
     *
     * @return void
     */
    public function __construct()
    {
        // 这里额外注意了：官方文档样例中只除外了『login』
        // 这样的结果是，token 只能在有效期以内进行刷新，过期无法刷新
        // 如果把 refresh 也放进去，token 即使过期但仍在刷新期以内也可刷新
        // 不过刷新一次作废
        $this->middleware('jwt.auth', ['except' => ['login', 'refresh']]);
        $this->middleware('jwt.refresh', ['except' => ['login', 'refresh']]);
        // 另外关于上面的中间件，官方文档写的是『auth:api』
        // 但是我推荐用 『jwt.auth』，效果是一样的，但是有更加丰富的报错信息返回
    }

    /**
     * @param Request $request
     * @return \Dingo\Api\Http\Response|mixed
     * @throws \Exception
     */
    public function login(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email|exists:users',
            'password' => 'required',
        ]);
        if ($validator->fails()) {
            return $this->errorBadRequest($validator);
        }
        $credentials = $request->only('email', 'password');

        if (!$token = Auth::guard('api')->attempt($credentials)) {
            return $this->errorBadRequest(trans('auth.failed'));
        }

        $authorization = new Authorization($token);
        Event::dispatch(new LoginEvent('api', $authorization->user()));

        return $this->response->item(
            $authorization,
            new AuthorizationTransformer()
        )->setStatusCode(201);
    }

    /**
     * Logout
     *
     * @return \Dingo\Api\Http\Response
     */
    public function logout()
    {
        Auth::guard('api')->logout();

        return $this->response->noContent();
    }

    /**
     * Get User Profile
     *
     * @return \Dingo\Api\Http\Response|mixed
     */
    public function user()
    {
        $user = Auth::guard('api')->user();

        return $this->response()->item($user, new UserTransformer());
    }
}
